<?php

namespace App\Admin\Controllers;

use App\AdminRole;
use App\AdminUser;
use App\User;
use Illuminate\Http\Request;

class UserController extends Controller
{

    //管理员列表页面
    public function index()
    {
        $users = AdminUser::paginate(10);

        return view('admin.user.index', compact('users'));
    }

    //管理员创建页面
    public function create()
    {

        return view('admin.user.add');
    }

    //创建操作
    public function store(Request $request)
    {
        //验证
        $this->validate($request, [
            'name' => 'required|min:2',
            'password' => 'required|min:6|max:16',
        ]);

        //逻辑
        $data = [
            'name' => $request->input('name'),
            'password' => bcrypt($request->input('password')),
        ];

        AdminUser::create($data);
        //渲染
        return redirect('/admin/users');
    }

    //用户角色页面
    public function role(AdminUser $user)
    {
        $roles = AdminRole::all();
        //获取当前用户的角色
        $myRoles = $user->roles;
        return view('admin.user.role', compact('roles', 'myRoles', 'user'));
    }

    //储存用户角色
    public function storeRole(AdminUser $user)
    {
        $this->validate(request(), [
            'roles' => 'required|array'
        ]);

        $roles = AdminRole::findMany(request('roles'));
        $myRoles = $user->roles;

        //要增加的
        $addRoles = $roles->diff($myRoles);
        foreach ($addRoles as $role) {
            $user->assignRole($role);
        }

        //要删除的
        $deleteRoles = $myRoles->diff($roles);
        foreach ($deleteRoles as $role) {
            $user->deleteRole($role);
        }

        return back();
    }


}